/*
** getnextline.c for get_next_line in /home/jeanma_d//Damien/CPE/GetNextLine
** 
** Made by damien jeanmaire
** Login   <jeanma_d@epitech.net>
** 
** Started on  Wed Nov 23 20:46:23 2011 damien jeanmaire
** Last update Mon Apr 30 17:59:35 2012 canh-kiet le
*/

#include	"my.h"

static int	fill_buff(int fd, int *r_nb, char *r_buff, int *i)
{
  if (*i == *r_nb)
    {
      *i = 0;
      if ((*r_nb = read(fd, r_buff, BUFF_SIZE)) == 0)
	return (0);
      else if (*r_nb == -1)
	return (-1);
    }
  return (1);
}

char		*get_next_line(const int fd)
{
  static int	r_nb = 0;
  static char	r_buff[BUFF_SIZE];
  static int	i = 0;
  int		j;
  char		*line;
  int		rd_err;

  if (fill_buff(fd, &r_nb, r_buff, &i) <= 0)
    return (NULL);
  line = xmalloc((LINE_SIZE + 1) * sizeof(char));
  line[0] = 0;
  j = 0;
  while (r_buff[i] && r_buff[i] != '\n' && j < LINE_SIZE)
    {
      line[j++] = r_buff[i++];
      line[j] = '\0';
      if ((rd_err = fill_buff(fd, &r_nb, r_buff, &i)) == -1)
	return (NULL);
      if (rd_err == 0)
	return (line);
    }
  if (j != LINE_SIZE || (j == LINE_SIZE && r_buff[i] == '\n'))
    i++;
  return (line);
}
